package com.heima.Aop;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.heima.mapper.OperateLogMapper;
import com.heima.poji.OperateLog;
import com.heima.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.annotation.Retention;
import java.lang.reflect.Array;
import java.net.http.HttpRequest;
import java.time.LocalDateTime;
import java.util.Arrays;


@Slf4j
@Aspect
@Component
public class LogAspect {

    @Autowired
    private HttpServletRequest httpServletRequest;

     @Autowired
     private OperateLogMapper operateLogMapper;
     @Around("@annotation(com.heima.anno.LogAnno)")
    public Object RecordLog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
         //调用目标方法
         String jwt = httpServletRequest.getHeader("token");
         Claims claims = JwtUtil.parseJWT(jwt);
         Integer operateId = (Integer) claims.get("id");
         String className = proceedingJoinPoint.getTarget().getClass().getName();
         String methodName = proceedingJoinPoint.getSignature().getName();
         long start = System.currentTimeMillis();
         Object[] arys = proceedingJoinPoint.getArgs();
         String arys1 = Arrays.toString(arys);
         LocalDateTime localDateTime1 = LocalDateTime.now();

         Object result = proceedingJoinPoint.proceed();
         long end = System.currentTimeMillis();
         long time = end - start;

         String jsonResult = JSONObject.toJSONString(result);
         OperateLog operateLog = new OperateLog(null,operateId,localDateTime1,className,
                 methodName,arys1,jsonResult,time);
         operateLogMapper.insert(operateLog);
         return result;
     }
}
